//login.js
//获取应用实例
const app = getApp()
import {
  login,
  sengCode,
  phoneLogin,
  hshPhoneLogin,
  phoneLoginSengCode,
  register,
  decrypt,
  decrypt1,
  visitorLogin, //游客登录
  visitorPhoneLoginSengCode //游客手机发送验证码
} from '../../utils/http'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    v: app.globalData.v, //版本
    lang: app.vSwitch(), //版本
    theme: app.cSwitch(true), //主题色
    patternsTheme: app.globalData.patternsTheme, //主题色
    wxApp: app.config.wxApp,

    show: false,
    active: 0,
    phone: '',
    codePhone: '',
    sendCodeBtn: '获取验证码',
    sendCodeFlag: true,
    yhxy: true,
    phone2: '',
    codePhone2: '',
    sendCodeBtn2: '获取验证码',
    sendCodeFlag2: true,

    patternsIndex: 0, //当前模式
    phoneLoginFlag: false,

    hlogo:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('page', getCurrentPages())
    const menuButtonObject = wx.getMenuButtonBoundingClientRect();
    this.setData({
      backTop:menuButtonObject.top+5,
      hlogo:app.globalData.b_logo
    })
  },

  // 微信便捷登陆

  wxLogin() {
    let t = this;
    app.message().then(r => {
      t.wxLoginFunc();
    })
  },

  // 微信登录调用接口
  wxLoginFunc(code) {
    let t = this;
    this.getWxCode().then(() => {
      login({
        code: t.data.code
      }).then(r => {
        
        if (r.data && r.code==0) {
          wx.setStorageSync('token', r.data.token);
          wx.setStorageSync('userInfo', r.data.circleUser);
          wx.setStorageSync('type', r.data.circleUser.type);
          wx.setStorageSync('patterns', r.data.circleUser.isTourists == 2 ? true : false);
          wx.setStorageSync('feihui', r.data.circleUser.organizationalIsDetail == 2 ? true : false);
          app.globalData.patterns = r.data.circleUser.isTourists == 2 ? true : false;
          app.globalData.feihui = r.data.circleUser.organizationalIsDetail == 2 ? true : false;
          app.globalData.token = r.data.token;
          app.globalData.userInfo = r.data.circleUser;
          app.globalData.uid = r.data.circleUser.id;
          wx.showToast({
            title: '登录成功',
            icon: 'none',
            duration: 1500,
            mask: true,
            success: function (res) {
              if (r.data.circleUser.name || r.data.circleUser.headPic) {
                let pages = getCurrentPages();

                if (pages.length > 1) {
                  // let page = pages[pages.length - 2];
                  wx.navigateBack({
                    delta: 1,
                    // success: function (e) {
                    //   page.init();
                    // }
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/index/home',
                  })
                }
              } else {
                wx.reLaunch({
                  url: '/pages/mine/info/index',
                })
              }
            }
          })
          app.onLaunch();
        }else
        {
          wx.showToast({
            title: r.data,
            icon:'none'
          })
        }
      })
    })
  },


  // 手机登录
  PhoneLogin() {
    let t = this;
    if (wx.getUserProfile) {
      wx.getUserProfile({
        desc: '用于完善会员资料',
        complete: function (res) {
          if (res.errMsg == "getUserProfile:ok") {
            t.setData({
              headPic: res.userInfo.avatarUrl.substring(0, res.userInfo.avatarUrl.length - 3) + '0',
              nickName: res.userInfo.nickName,
            })
          }
          t.PhoneLogin2();
        }
      })
    } else {
      t.PhoneLogin2();
    }

  },
  PhoneLogin2() {
    let t = this;

    let regPhone = /^1[3|4|5|6|7|8|9]\d{9}$/;
    if (!regPhone.test(t.data.phone2)) {
      wx.showToast({
        title: '请输入正确格式的手机号',
        icon: 'none'
      })
      return false;
    }
    if (!t.data.codePhone2) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return false;
    }
    if (!t.data.yhxy) {
      wx.showToast({
        title: '请勾选用户协议',
        icon: 'none'
      })
      return false;
    }
    t.getWxCode().then(() => {
      var func;
      if (t.data.wxApp.duoLogin) {
        func = hshPhoneLogin;
      } else {
        func = phoneLogin;
      }
      func({
        phone: t.data.phone2,
        phoneCode: t.data.codePhone2,
        code: t.data.code,
        headPic: t.data.headPic ? t.data.headPic : '',
        name: t.data.nickName
      }).then(r => {
        if (r.httpCode != 200 && r.code != 0) {
          let title = '登录失败';
          if (r.message) {
            title = r.message;
          } else if (r.msg) {
            title = r.msg;  
          }
          wx.showToast({
            title: title,
            icon: 'none',
            duration: 2500,
            mask: true
          });
        } else {
          if (r.data) {

            wx.setStorageSync('token', r.data.token);
            wx.setStorageSync('userInfo', r.data.circleUser);
            wx.setStorageSync('type', r.data.circleUser.type);
            wx.setStorageSync('patterns', r.data.circleUser.isTourists == 2 ? true : false);
            wx.setStorageSync('feihui', r.data.circleUser.organizationalIsDetail == 2 ? true : false);
            app.globalData.feihui = r.data.circleUser.organizationalIsDetail == 2 ? true : false;
            app.globalData.patterns = r.data.circleUser.isTourists == 2 ? true : false;
            app.globalData.token = r.data.token;
            app.globalData.userInfo = r.data.circleUser;
            app.globalData.uid = r.data.circleUser.id;
            wx.showToast({
              title: '登录成功',
              icon: 'none',
              duration: 1500,
              mask: true,
              success: function (res) {
                if (r.data.circleUser.name && r.data.circleUser.organizationalId) {
                  let pages = getCurrentPages();

                  if (pages.length > 1) {
                    // let page = pages[pages.length - 2];
                    wx.navigateBack({
                      delta: 1,
                      // success: function (e) {
                      //   page.init();
                      // }
                    })
                  } else {
                    wx.switchTab({
                      url: '/pages/index/home',
                    })
                  }

                } else {
                  wx.reLaunch({
                    url: '/pages/mine/info/index',
                  })
                }
              }
            })
            app.onLaunch();
          }

        }
      })
    })

  },

  // 游客手机登录
  visitorPhoneLogin() {
    let t = this;
    if (wx.getUserProfile) {
      wx.getUserProfile({
        desc: '用于完善会员资料',
        complete: function (res) {
          if (res.errMsg == "getUserProfile:ok") {
            t.setData({
              headPic: res.userInfo.avatarUrl.substring(0, res.userInfo.avatarUrl.length - 3) + '0',
              nickName: res.userInfo.nickName,
            })
          }
          t.visitorPhoneLogin2();
        }
      })
    } else {
      t.visitorPhoneLogin2();
    }

  },
  visitorPhoneLogin2() {
    let t = this;
    let regPhone = /^1[3|4|5|6|7|8|9]\d{9}$/;
    if (!regPhone.test(t.data.phone2)) {
      wx.showToast({
        title: '请输入正确格式的手机号',
        icon: 'none'
      })
      return false;
    }
    if (!t.data.codePhone2) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return false;
    }
    if (!t.data.yhxy) {
      wx.showToast({
        title: '请勾选用户协议',
        icon: 'none'
      })
      return false;
    }
    t.getWxCode().then(() => {
      visitorLogin({
        phone: t.data.phone2,
        phoneCode: t.data.codePhone2,
        code: t.data.code,
        headPic: t.data.headPic ? t.data.headPic : '',
        name: t.data.nickName
      }).then(r => {
        if (r.httpCode != 200 && r.code != 0) {
          let title = '登录失败';
          if (r.message) {
            title = r.message;
          } else if (r.msg) {
            title = r.msg;
          }
          wx.showToast({
            title: title,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        } else {
          if (r.data) {
            wx.setStorageSync('token', r.data.token);
            wx.setStorageSync('userInfo', r.data.circleUser);
            wx.setStorageSync('type', r.data.circleUser.type);
            wx.setStorageSync('patterns', r.data.circleUser.isTourists == 2 ? true : false);
            wx.setStorageSync('feihui', r.data.circleUser.organizationalIsDetail == 2 ? true : false);
            app.globalData.feihui = r.data.circleUser.organizationalIsDetail == 2 ? true : false;
            app.globalData.token = r.data.token;
            app.globalData.userInfo = r.data.circleUser;
            app.globalData.uid = r.data.circleUser.id;
            app.globalData.patterns = r.data.circleUser.isTourists == 2 ? true : false;
            wx.showToast({
              title: '登录成功',
              icon: 'none',
              duration: 1500,
              mask: true,
              success: function (res) {
                let pages = getCurrentPages();
                if (pages.length > 1 && pages[pages.length - 2].route != 'pages/index/index') {
                  wx.navigateBack({
                    delta: 1,
                  })
                } else {
                  wx.reLaunch({
                    url: t.data.v ? '/pages/share/list' : '/pages/activity/home',
                  })
                }

              }
            })
            app.onLaunch();
          }

        }
      })
    })

  },

  // 游客模式
  setPatterns() {
    let t = this;
    wx.setStorageSync('patterns', true);
    app.globalData.patterns = true;
    let pages = getCurrentPages();
    if (pages.length > 1 && pages[pages.length - 2].route != 'pages/index/index') {
      wx.navigateBack({
        delta: 1,
      })
    } else {
      wx.reLaunch({
        url: t.data.v ? '/pages/share/list' : '/pages/activity/home',
      })
    }
  },

  sendCode2() {
    let t = this;
    // console.log(vm.phone);
    return new Promise((resolve, reject) => {
      let regPhone = /^1[3|4|5|6|7|8|9]\d{9}$/;
      if (!regPhone.test(t.data.phone2)) {
        wx.showToast({
          title: '请输入正确格式的手机号',
          icon: 'none'
        })
        return false;
        resolve();
      }
      t.setData({
        sendCodeFlag2: false
      })
      let func;
      if (t.data.patternsIndex) {
        func = visitorPhoneLoginSengCode;
      } else {
        func = phoneLoginSengCode;
      }

      // visitorPhoneLoginSengCode
      // 发送验证码
      func({
        phone: t.data.phone2
      }).then(res => {
        if (res.httpCode == 200 || res.code == 0) {
          wx.showToast({
            title: '发送成功',
          })
          t.setData({
            sendCodeFlag2: false
          })
          t.countDown2(1, 60);
        } else {
          t.setData({
            sendCodeFlag2: true
          })
        }
        resolve();
      }).catch(err => {
        t.setData({
          sendCodeFlag2: true
        })
        reject(err);
      });
    });
  },
  countDown2(num, m) {
    let t = this;
    if (num == m) {
      t.setData({
        sendCodeBtn2: '重新发送',
        sendCodeFlag2: true
      })

    } else {
      var printnr = m - num;
      t.setData({
        sendCodeBtn2: printnr + "s",
      })

      setTimeout(function () {
        t.countDown2(num, printnr);
      }, 1000);
    }
  },


  // 获取手机号
  getPhoneNumber(e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    let t = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      this.getWxCode().then(() => {
        decrypt({
          code: t.data.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }).then(r => {
          if (r.data) {
            t.setData({
              phone2: r.data,
              codePhone2:'888888'
            })

            t.getWxCode().then(() => {
               t.PhoneLogin2()
            })
          }
        })
      })
    }
    // this.setData({
    //   active: 1
    // })
  },

  // 模式切换
  changePatterns(e) {
    this.setData({
      patternsIndex: parseInt(e.mark.index),
      // phoneLoginFlag: parseInt(e.mark.index) == 1 ? true : false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      theme: app.cSwitch(true), //主题色
      wxApp: app.config.wxApp
    })
    this.wxLogin();
  },

  getWxCode() {
    let t = this;
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            // console.log(res);
            t.setData({
              code: res.code
            })
            resolve();
          } else {
            wx.showToast({
              title: '获取微信code失败！',
              icon: 'none'
            })
            console.log('登录失败！' + res.errMsg)
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '获取微信code失败！',
            icon: 'none'
          })
        }
      })
    })

  },

  sendCode() {
    let t = this;
    // console.log(vm.phone);
    return new Promise((resolve, reject) => {
      let regPhone = /^1[3|4|5|6|7|8|9]\d{9}$/;
      if (!regPhone.test(t.data.phone)) {
        wx.showToast({
          title: '请输入正确格式的手机号',
          icon: 'none'
        })
        return false;
        resolve();
      }
      t.setData({
        sendCodeFlag: false
      })
      // 发送验证码
      sengCode({
        phone: t.data.phone
      }).then(res => {
        if (res.httpCode == 200 || res.code == 0) {
          wx.showToast({
            title: '发送成功',
          })
          t.setData({
            sendCodeFlag: false
          })
          t.countDown(1, 60);
        } else {
          t.setData({
            sendCodeFlag: true
          })
        }
        resolve();
      }).catch(err => {
        t.setData({
          sendCodeFlag: true
        })
        reject(err);
      });
    });
  },
  countDown(num, m) {
    let t = this;
    if (num == m) {
      t.setData({
        sendCodeBtn: '重新发送',
        sendCodeFlag: true
      })

    } else {
      var printnr = m - num;
      t.setData({
        sendCodeBtn: printnr + "s",
      })

      setTimeout(function () {
        t.countDown(num, printnr);
      }, 1000);
    }
  },

  submit() {
    let t = this;
    wx.getUserProfile({
      desc: '用于完善会员资料',
      complete: function (res) {
        if (res.errMsg == "getUserProfile:ok") {
          t.setData({
            headPic: res.userInfo.avatarUrl.substring(0, res.userInfo.avatarUrl.length - 3) + '0',
            nickName: res.userInfo.nickName,
          })
        }
        let regPhone = /^1[3|4|5|6|7|8|9]\d{9}$/;
        if (!regPhone.test(t.data.phone)) {
          wx.showToast({
            title: '请输入正确格式的手机号',
            icon: 'none'
          })
          return false;
        }
        if (!t.data.codePhone) {
          wx.showToast({
            title: '请输入验证码',
            icon: 'none'
          })
          return false;
        }
        if (!t.data.yhxy) {
          wx.showToast({
            title: '请勾选用户协议',
            icon: 'none'
          })
          return false;
        }
        wx.showLoading({
          title: '请稍等...',
          mask: true,
        })
        // wx.getUserInfo({
        //   complete: function (res) {
        //     if (res.errMsg == "getUserInfo:ok") {
        //       t.setData({
        //         headPic: res.userInfo.avatarUrl.substring(0, res.userInfo.avatarUrl.length - 3) + '0',
        //       })
        //     }
        t.getWxCode().then(() => {
          register({
            phone: t.data.phone,
            phoneCode: t.data.codePhone,
            code: t.data.code,
            headPic: t.data.headPic ? t.data.headPic : ''
            // wxCode: t.data.code,
            // nickName: t.data.nickName,
            // avatarUrl: t.data.avatarUrl
          }).then(r => {
            if (r.httpCode != 200 && r.code != 0) {
              let title = '注册失败';
              if (r.message) {
                title = r.message;
              } else if (r.msg) {
                title = r.msg;
              }
              wx.showToast({
                title: title,
                icon: 'none',
                duration: 1500,
                mask: true
              });
            } else {
              wx.showToast({
                title: '注册成功',
                icon: 'none',
                mask: 'true'
              })
              setTimeout(() => {
                t.wxLoginFunc();
              }, 1500)
            }
          })
        })
      }
    })

  },
  tabChange(e) {
    this.setData({
      active: e.mark.index
    })
  },
  open() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },

  phoneLogin() {
    this.setData({
      phoneLoginFlag: true
    })
  },

  wxLoginBtn() {
    this.setData({
      phoneLoginFlag: false
    })
  },

  goback()
  {
    wx.switchTab({
      url: '../index/home',
    })
  },

  // goWxApp() {
  //   wx.navigateToMiniProgram({
  //     appId: 'wxc8c6230b1ad460de',
  //     path: 'pages/index/index',
  //     success(res) {
  //       // 打开成功
  //     }
  //   })
  // },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.share();
  }
})